package com.fancy.babel.service.impl;

import com.fancy.babel.dao.CategoryDao;
import com.fancy.babel.entity.CategoryEntity;
import com.fancy.babel.service.CategoryService;
import com.fancy.babel.utils.PageUtils;
import com.fancy.babel.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取商品分类集合
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查询出所有分类
        List<CategoryEntity> categoryEntityList = categoryDao.selectList(null);
        //2、组装成父子的树形结构
        // 获取一级分类
//        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
//                categoryEntity.getParentCid() == 0
//                ).collect(Collectors.toList());
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
            // 寻找并设置子菜单
            menu.setChildren(getChildrens(menu,categoryEntityList));
            return menu;
        }).sorted((menu1, menu2) -> {
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 逻辑删除节点
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {

        categoryDao.deleteBatchIds(asList);
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> list){

        List<CategoryEntity> children = list.stream().filter(categoryEntity -> {
            // 父级菜单跟子集菜单对比
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            // 获取子集
            categoryEntity.setChildren(getChildrens(categoryEntity,list));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}